package com.trainingcloud.action.auth;


import java.util.Date;

import com.trainingcloud.Globals;
import com.trainingcloud.XMLSerializer;
import com.trainingcloud.action.BaseAction;
import com.trainingcloud.dao.UserDAO;
import com.trainingcloud.entity.User;
import com.trainingcloud.exception.DAOException;
import com.trainingcloud.exception.SystemException;

public class LoginAction extends BaseAction
{
	private String loginName;
	private String loginPassword;
	
	public LoginAction() throws SystemException 
	{
		super();
	}

	@Override
	public String call() throws DAOException, SystemException 
	{
		UserDAO userDAO = new UserDAO();
		
		User user = userDAO.getUserByLoginName(loginName);
		if(user==null)
		{
			return "Invalid login name.";
		}
		if(user.getLoginPassword().compareTo(loginPassword)!=0)
		{
			return "Invalid login password.";
		}

		user.setLatestLoginTime(new Date());
		userDAO.updateUser(user);
		
		String token = Globals.getTokenManager().generateOneToken(user.getId());
		responseElement.addElement("token")
			.addText(token);
		XMLSerializer.userToXML(user, responseElement);
		
		
		return null;
	}
	
	public String getLoginName() 
	{
		return loginName;
	}

	public void setLoginName(String loginName) 
	{
		this.loginName = loginName;
	}

	public String getLoginPassword() 
	{
		return loginPassword;
	}

	public void setLoginPassword(String loginPassword) 
	{
		this.loginPassword = loginPassword;
	}

}
